package com.fingard.dsp.bank.directbank.wrcb01;

import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.net.ITcpClient;
import com.fingard.net.TcpPortClient;
import com.fingard.net.TcpReceiver;
import com.fingard.text.StringHelper;

public class WRCB01Base extends DirectBase implements ITcpClient {
    protected String[] sendToBank(String p_reqStr) throws Exception {
        byte[] tmpBytes = p_reqStr.getBytes(getCharset());
        int XMLlength = tmpBytes.length;
        StringBuilder reqContext = new StringBuilder(p_reqStr).insert(0, String.format("%010d", XMLlength));
        String[] retStr = new String[]{"", ""};
        WriteBankUrlLogLn("请求银行的地址" + bankFront.serverIP + ":" + bankFront.serverPort);
        WriteBankLogStep2(reqContext.toString());
        //发送银行前置
        TcpPortClient tmpClient = new TcpPortClient(bankFront.serverIP, Integer.parseInt(bankFront.serverPort), this);
        TcpReceiver tmpReceiver = tmpClient.sendMessage(reqContext.toString().getBytes(getCharset()));
        retStr[0] = tmpReceiver.connState;
        retStr[1] = tmpReceiver.getFullString(getCharset());
        if (StringHelper.isNullOrEmpty(retStr[1])) {
            retStr[1] = tmpReceiver.getConnMsg();
        } else {
            if (retStr[1].indexOf("<Message") != -1) {
                retStr[1] = retStr[1].substring(retStr[1].indexOf("<Message"));
            } else {
                retStr[1] = retStr[1];
            }
        }
        WriteBankLogStep3(retStr[1]);
        return retStr;

    }

    protected String getCharset() {
        return getBankConfig().getCharset("UTF-8");
    }

    @Override
    public void getContentLength(TcpReceiver p_receiver) throws Exception {
        if (p_receiver.contentLength == -1) {
            String tmpCharset = getCharset();
            String tmpRecNow = new String(p_receiver.recBytes, 0, p_receiver.readedLength, tmpCharset);
            if (tmpRecNow.contains("</Message>")) {
                p_receiver.contentLength = p_receiver.readedLength;
                p_receiver.contentStartIndex = 0;
            }
        }
    }
}
